package com.example.work7


import android.annotation.SuppressLint
import android.content.*
import android.content.pm.PackageManager
import android.os.Build

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.SeekBar
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

import kotlin.concurrent.thread

const val MyReceiverAction = "cn.edu.sicnu.musicplayer.newmusic"

class MainActivity(val yourBroadcastReceiver: BroadcastReceiver?) : AppCompatActivity() ,ServiceConnection{
    var binder: MusicService.MusicBinder ?= null

    val TAG = "MainActivity"
    lateinit var receiver : MusicReceiver

    @SuppressLint("UnspecifiedRegisterReceiverFlag", "MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        val intentFilter = IntentFilter("com.example.ACTION")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(yourBroadcastReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(yourBroadcastReceiver, intentFilter)
        }

        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
                0
            )
        } else {
            startMusicService()
        }

        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(
                seekBar: SeekBar,
                progress: Int,
                fromUser: Boolean
            ) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })


    }

    fun startMusicService() {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,1)
        startService(intent)
        bindService(intent,this,Context.BIND_AUTO_CREATE)
    }

    fun onPlay(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,1)
        startService(intent)
    }

    fun onPause(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,2)
        startService(intent)
    }

    fun onStop(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,3)
        startService(intent)
    }

    fun onNext(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,4)
        startService(intent)
    }

    fun onPrev(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,5)
        startService(intent)
    }



    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        startMusicService()
    }



    override fun onDestroy() {
        super.onDestroy()
        val intent = Intent(this, MusicService::class.java)
        unregisterReceiver(receiver)
        unbindService(this)
        stopService(intent)
    }


    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        val textView_mn = findViewById<android.widget.TextView>(R.id.textView_mn)
        val textView_count = findViewById<android.widget.TextView>(R.id.textView_count)
        binder = service as MusicService.MusicBinder
        thread {
            while (binder != null) {
                Thread.sleep(1000)
                runOnUiThread {
                    seekBar.max = binder!!.duration
                    textView_count.text = "${binder!!.currentIndex+1}/${binder!!.size}"
                    textView_mn.text = binder!!.musicName
                    seekBar.progress = binder!!.currentPosition
                }
            }
        }
    }
    inner class MusicReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val seekBar = findViewById<SeekBar>(R.id.seekBar)
            val textView_mn = findViewById<android.widget.TextView>(R.id.textView_mn)
            val textView_count = findViewById<android.widget.TextView>(R.id.textView_count)
            val op = intent.getIntExtra("operate",0)
            if (op == 1){
                seekBar.max = binder!!.duration
                textView_mn.text = binder!!.musicName
                textView_count.text = "${binder!!.currentIndex+1}/${binder!!.size}"
            }
        }

    }


    override fun onServiceDisconnected(name: ComponentName?) {
        TODO("Not yet implemented")
    }

}